'use strict';

const BaseController = require('../core/base');

const getTreeDept = function (rootList = [], replaceField = {}) {
  const { parentId = 'parentId', id = 'id' } = replaceField;
  const topList = [];
  const unTopList = [];
  rootList.forEach(item => {
    if (Number(item[parentId]) === 0) {
      topList.push(item);
    } else {
      unTopList.push(item);
    }
  });
  const addChildren = (node, dataList) => {
    const children = dataList
      .filter(item => Number(item[parentId]) === Number(node[id]))
      .map(item => addChildren(item, dataList));
    if (children.length) {
      node.children = children;
    }
    return node;
  };

  return topList.map(root => addChildren(root, unTopList));
};

class DeptController extends BaseController {
  // 获取角色信息
  async deptForm() {
    const query = this.ctx.params;
    const { dept } = this.ctx.service;
    const result = await dept.findOne(query);
    if (result) {
      this.success(result);
    } else {
      this.fail();
    }
  }
  async tree() {
    // 返回树形结构
    const { dept } = this.ctx.service;
    const rootList = await dept.findAll();
    const treeList = getTreeDept(rootList);
    this.success(treeList);
  }
  // 下拉列表
  async options() {
    // 返回树形结构
    const { dept } = this.ctx.service;
    let rootList = await dept.findAll();
    rootList = rootList.map(item => {
      const { name: label, id: value, parentId } = item;
      return {
        label,
        value,
        parentId,
      };
    });
    const treeList = getTreeDept(rootList, { parentId: 'parentId', id: 'value' });
    this.success(treeList);
  }

  // 添加和编辑
  async save() {
    const { name } = this.ctx.request.body;
    const { id } = this.ctx.params;
    // 校验
    if (!name) return this.fail('部门名称不能为空');
    const data = this.ctx.request.body;
    const { dept } = this.ctx.service;
    if (!id) {
      const result = await dept.save(this.ctx.request.body);
      if (!result) {
        return this.fail('新增失败');
      }
      this.success();
    } else {
      data.id = id;
      const result = await dept.save(data);
      if (!result) {
        return this.fail('更新失败');
      }
      this.success({});
    }
  }
  // 删除
  async remove() {
    let { ids } = this.ctx.params;
    ids = typeof ids === 'string' ? ids.split(',').map(v => Number(v)) : [];
    const { dept } = this.ctx.service;
    let count = 0;
    if (ids.length) {
      for (const id of ids) {
        const ret = await dept.remove(id);
        if (ret) count += 1;
      }
      this.success(count, `共删除${count}条数据`);
    } else {
      this.fail('参数错误');
    }
  }
}

module.exports = DeptController;
